/*
 * @Description:
 * @Author: zhaokun
 * @Date: 2022-02-22 09:41:42
 * @LastEditTime: 2022-02-22 16:30:14
 * @FilePath: \user\rpc\taskpool\taskpool.go
 */
package taskpool

import (
	"reflect"
	"user/rpc/internal/svc"
)

type Pool interface {
	RunTask(*Task)     //同步运行协程
	RunTaskAsyn(*Task) //异步运行协程
	Count()            //获取在运行的任务总数
}

type TaskPool struct {
	svcCtx *svc.ServiceContext
	count  int
}

func NewTaskPool(svcCtx *svc.ServiceContext) *TaskPool {
	pool := &TaskPool{}
	pool.svcCtx = svcCtx
	pool.count = 0
	return pool
}

func (t *TaskPool) RunTask(task interface{}) {
	//动态调用方法
	go func() {
		args := make([]reflect.Value, 1)
		args[0] = reflect.ValueOf(t.svcCtx)
		reflect.ValueOf(task).MethodByName("Handler").Call(args)
		t.count++
	}()
}

func (t *TaskPool) RunTaskAsyn(task *Task) {
	args := make([]reflect.Value, 1)
	args[0] = reflect.ValueOf(t.svcCtx)
	reflect.ValueOf(task).MethodByName("AsyHandler").Call(args)
	t.count++
}

func (t *TaskPool) Count() int {
	return t.count
}
